package com.zhz.interceptor;

import com.zhz.annocation.Idempotent;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @program: idempotent_token
 * @description: 新拦截器
 * @author: zhanghz001
 * @create: 2021-03-15 08:44
 **/
public class IdempotentInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是方法的,就不要拦截了
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //强转得到方法名
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Idempotent annotation = method.getAnnotation(Idempotent.class);
        if (annotation != null) {
            checkToken(request);
        }
        
        return true;
    }
    
    @Autowired
    private RedisTemplate redisTemplate;
    
    private void checkToken(HttpServletRequest request) {
        
        //获取令牌
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("非法参数");
        }
        
        //校验令牌
        if (!redisTemplate.delete(token)) {
            //删除失败
            throw new RuntimeException("重复请求");
        }
        
    }
}
